package com.jml.juc;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import org.junit.Test;

/**
 * @author:jml
 * @date: 2019/5/24 11:07
 * @description：
 */
public class 锁降级 {

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static ReadLock r = lock.readLock();
    private static WriteLock w = lock.writeLock();
    private volatile boolean update = false;

    @Test
    public void processData() {
        r.lock();
        if (!update) {
            r.unlock();
            w.lock();
            try {
                if (!update) {
                    //数据准备
                    update = true;
                }
                r.lock();
            } finally {
                w.unlock();
            }
            //完成锁降级，写锁降级为读锁
            try {
                //数据逻辑处理
            } finally {
                r.unlock();
            }
        }
    }

    Map map = new HashMap();

    @Test
    public void processData1() {
        System.out.println("开启写锁");
        w.lock();

        map.put("as", "zxz");

        System.out.println("开启读锁");
        r.lock();
        System.out.println(map.get("as"));

        map.put("zz", "zzz");

        System.out.println(map.get("zz"));

        System.out.println("释放写锁");
        w.unlock();
        System.out.println("释放读锁");
        r.unlock();
        System.out.println("end");
    }


    @Test
    public void t2() throws IllegalAccessException {
        TBean tBean = new TBean();

        TBean tBeanSon = new TBean(){
            private Integer age = 15;
        };
        Class<? extends TBean> aClass = tBeanSon.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();


        for (Field  field: declaredFields) {
            field.setAccessible(true);
            System.out.println(field.getName()+"  :" + field.get(tBeanSon).toString());
        }

        Class<?> superclass = aClass.getSuperclass();
        System.out.println(superclass.getClass().getName());

//        System.out.println(tBeanSon.getClass().getName());
//
//        System.out.println(tBean.getClass().equals(tBeanSon.getClass()));





    }

}
